<?php
namespace App\ModelStatistic;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Input;

class UserConvRate extends Model {
    

    // 获取各个阶段
    public static function stageList($opk = null) {
        $stage_list = [
            'SDK_Init_Begin' => '游戏黑屏前android',
            // 'SDK_Init_Finish' => '游戏黑屏后android',
            'OpenGame' => '打开游戏Unity',
            'CDN_DownloadResult' => 'CDN完成',
            'StartLoadingGame' => '登录场景',
            'AchieveLogin_BtnClick' => '登录点击',
            'StartGameBtn' => '开始进入游戏',
            'CreateRoleBtn' => '创建角色按钮',
            'Guide_AchieveMove' => '完成移动教学',
            'S.login' => '有角色登录',
        ];
        return $stage_list;
    }
	public function paginate()
    {
        

    	$perPage = Request::get('per_page', 1000);

        $page = Request::get('page', 1);
        
        $start = ($page-1)*$perPage;

        $qdCond = StatisticCommon::remainChartDate(Request::get('select_time'), 0);
        $area_select = Request::get('select_area');
        \Log::debug("------------", [$area_select]);
        $area_ids = [-1];
        if (!($area_select)) {
            // $area_select = \App\Models\Area::getValidAreas();
            // $area_ids[] = array_merge($area_ids, $area_select);
        } else {
            $area_ids[] = $area_select;
        }
        
        $list = $this->getDataByGuid($qdCond['start'], $qdCond['end'], $area_ids);
        
        //\App\ModelStatistic\StatisticCommon::arrayFieldSort($list, 'retain_time');
        
        $total = count($list);
        $list = static::hydrate($list);
        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }
    // 
    public function getDataByGuid($begin, $end, $area_ids){
        $imeis = $this->getImeiSignle($begin, $end);
        $count = count($imeis);
        $result = $total_item = [];
        if (empty($imeis)) {
            return [];
        }
       
        $area_ids = array_flip(array_flip($area_ids));
        \Log::debug("[IMEI_DATA][GET][AREA]", [$area_ids, $imeis]);
        foreach ($area_ids as $area_id ) {
            $tmp = $this->getDataByGuidSingle($begin, $end, $area_id, $imeis);
            foreach ( $tmp as $opk => $num) {
                $opk = str_replace('.', '___', $opk); // 处理服务端S.数据
                $total_item[$opk] += $num;
                $tmp[$opk] = $num;
            }
            $tmp['area'] = $area_id;
            \Log::debug("[IMEI_DATA][FOR_BY_AREA]AREA[".$area_id."]", [$tmp]);
            $result[] = $tmp;
        }
        $total_item['area'] = "TOTAL:$count";
        $result[] = $total_item;
        \Log::debug("[IMEI_DATA][GET][END]");
        return $result;
    }

    // 查询此阶段所有的IMEI
    public function getImeiSignle($begin, $end){
        \App\Models\Area::RemoteBgsiSelectByArea(-1);
        \Log::info("[IMEI_SOURCE]BEGIN[$begin]E[$end]");
        $list = \DB::connection('remote_bgsi')->table('imei_log')->select('imei')
        ->where('created_at', '>=', $begin)->where('created_at', '<', $end)->groupBy('imei')->get();
        
        if (empty($list)) {
            $this->CloseRemoteConn();
            return [];
        }
        $arr = [];
        foreach ($list as $obj) {
            $arr[] = $obj->imei;
        }
        $this->CloseRemoteConn();
        $count = count($arr);
        \Log::info("[IMEI_SOURCE]COUNT[$count]END");
        return $arr;
    }

    // 单独查询某个区的imei 统计
    public function getDataByGuidSingle($begin, $end, $area_id, $imeis) {
        $runtime = time();
        
        \Log::debug("[IMEI_DATA][SINGLE]AREA[" . $area_id . "]");
        $result = [];
        $ret = \App\Models\Area::RemoteBgsiSelectByArea($area_id);
        if (!$ret) {
            return $result;
        }
        // 没办法只能在循环里写统计sql了 每一项的 group by  语句
        foreach (self::stageList() as $opk =>$label) {
            $rw = \DB::connection('remote_bgsi')->table('behavior_log')
            ->whereIn('imei', $imeis)->where('op', $opk)
            ->groupBy('imei');
            $rwg = $rw->get();
            $result[$opk] = $rwg->count();
            // \Log::debug("[IMEI_DATA][SINGLE]OP[" .$opk. "]SQL[".$rw->toSql()."]");   
        }
        $this->CloseRemoteConn();
        $runtime = time() - $runtime;
        \Log::debug("[IMEI_SINGLE][GET]AREA[".$area_id."]RUNTIME[".$runtime."]");
        return $result;
    }


    // 关闭远程数据库连接
    public function CloseRemoteConn()
    {
        if ( ! \Config::get("database.connections.remote_bgsi") ) {
            return;
        }
        
        \DB::disconnect('remote_bgsi');
    }

    public static function getConvTotalData() {
        $qdCond = StatisticCommon::remainChartDate(Request::get('select_time'), 0);
        \App\Models\Area::RemoteBgsiSelectByArea(-1);

        $rw = \DB::connection('remote_bgsi')->table('imei_log');
        $rw->where('created_at', '>=', $qdCond['start'])->where('created_at', '<', $qdCond['end']);
        $rw->groupBy('imei');

        $rtn['count_open'] = $rw->get()->count();

        $rw->where('account', ">", 0);
        $rtn['count_account'] = $rw->get()->count();
        $rw->where('player_id', ">", 0);
        $rtn['count_role'] = $rw->get()->count();
        \Log::info("[USER_CONV][created_at]", [$qdCond]);
        return $rtn;
    }
}